local ExcelItem = require("excel.Item")
local WSConfig = require("excel.CopyWushuang").wushuang
local Lang = require("common.Lang")
local RandomLogic = require("common.RandomLogic")
local HtmlUtil = require("common.HtmlUtil")
local Msg = require("core.Msg")
local Obj = require("core.Obj")
local ObjHuman = require("core.ObjHuman")
local Cmds = require("buffer.Cmds")
local Buffer = require("buffer.Buffer")
local Skill = require("skill.Skill")
local BagLogic = require("bag.BagLogic")
local ItemDefine = require("bag.ItemDefine")
local RoleAttr = require("role.RoleAttr")
local ExcelSkill = require("excel.Skill")
local TaskCallbacks = require("task.TaskCallbacks")
local Broadcast = require("broadcast.Broadcast")
local ExcelLevelRewardConf = require("excel.LevelReward")
local RoleDefine = require("role.RoleDefine")
local HorseLogic = require("horse.HorseLogic")
local BaowuLogic = require("baowu.BaowuLogic")
local ShenbingLogic = require("shenbing.ShenbingLogic")
local Grid = require("bag.Grid")
local PetLogic2 = require("pet.PetLogic2")
local PetConfig = require("excel.Pet").other
local VipLogic = require("vip.VipLogic")
local Wushuang = require("copy.Wushuang")
local TaskDuanceng = require("task.Duanceng")
local ActivityNotify  = require("activity.Notify")
local Config = require("Config")
local PetLogic = require("pet.PetLogic")

useSkillData = useSkillData or {}

data = {}
local function send_err(human, err, a, b, c)
    if data.no_send_err then
        return
    end
    if not err then
        assert()
    end
    if a then
        err = string.format(err, a, b, c)
    end
    local msgRet = Msg.gc.GC_BROADCAST
    msgRet.type = Lang.MOUSE
    msgRet.msg = err
    Msg.send(msgRet, human.fd)
end

local function getUseDesc(human, index)
    local grid = BagLogic.getGridByIndex(human, index)
    local showUseDesc = ItemDefine.getValue(grid.id, "showUseDesc")
    local useDesc = ItemDefine.getValue(grid.id, "useDesc")
    if showUseDesc and showUseDesc == 1 and useDesc and #useDesc ~= 0 then
        return useDesc
    end
end

cmd = {}
function cmd.buf(human, arg1)
    local itemID = data.itemID
    local coolGroup = ItemDefine.getValue(itemID, "coolGroup")
    if coolGroup == 1 then	-- check hp
        if ObjHuman.getHpMax(human) <= human.db.hp then
            return send_err(human, Lang.ITEM_ERR_HP_FULL)
        end
    end
    if type(arg1) == "table" then
        for k, v in pairs(arg1) do
            Buffer.add(v, human, human)
        end
    else
        Buffer.add(arg1, human, human)
    end
    return true
end

--local function getIndexByGroup(human, tmpIndex, group)
--    for index, grid in pairs(human.db.bag) do
--        if index ~= 0 and index ~= tmpIndex and grid and ItemDefine.isItem(grid.id)
--            and ItemDefine.getValue(grid.id, "coolGroup") == group then
--            return index
--        end
--    end
--end

function cmd.hp(human, arg1)
    local hpMax = ObjHuman.getHpMax(human)
    if hpMax <= human.db.hp then
        return send_err(human, Lang.ITEM_ERR_HP_FULL)
    end
    local addHp = 0
    if arg1 > 1 then			-- add value
        addHp = arg1 * ObjHuman.getAttr(human, RoleDefine.HP_RATE)
        ObjHuman.setHp(human, human.db.hp + addHp)
        addHp = arg1
    else						-- add rate
        addHp = hpMax * (arg1+ObjHuman.getAttr(human, RoleDefine.HP_RATE))
        ObjHuman.setHp(human, human.db.hp + addHp)
    end
    return true
end
local libaoGrids = {}
function cmd.libao(human, arg)
    local index = data.index
    local bagGrid = BagLogic.getGridByIndex(human, index)
    local nTempGrid = {}
    if not bagGrid then
        return
    end

    for k in pairs(libaoGrids) do
        libaoGrids[k] = nil
    end

    local arg1 = arg[1]
    if not arg1 then
        return false
    end
    local arg2 = arg[2]

    local cnt = #arg1
    if arg2 then
        cnt = cnt + arg2[0]
    end


    --列表1格式：{物品ID，物品数量1，物品数量2, 绑定规则, 绑定几率，{排除品质}，强化等级, 神兵ID，性别}，……
    local left = BagLogic.getLeftGrids(human)
    if cnt > left then
        return send_err(human, Lang.ITEM_ERR_NO_BAG_CAP_ON_LIBAO)
    end

    local bind
    for _, v in ipairs(arg1) do
        if ItemDefine.spobj.yinliang[v[1]] then
            if not ObjHuman.canUpdateYinliang(human, v[2]) then
                return send_err(human, Lang.ITEM_ERR_YINLIANG_FULL)
            end
        end
    end

    --必出道具逻辑
    for i = 1, #arg1 do
        local conf = arg1[i]
        local id = conf[1]
        local cnt = conf[2]
        local cnt1 = conf[3]
        local bindRule = conf[4]
        local bindCnt = conf[5]
        local qualityOut = conf[6]
        local strengthenLv = conf[7]
        local shenbingid =  conf[8]
        local sex = conf[9]

        if (sex == 0 or human.db.sex == sex) and (shenbingid == 0 or human.db.shenbing[0].id == shenbingid) then					-- 性别
            if itemIndex then
                if itemBind and bindRule == 1 then
                    bind = true
                else
                    local bindRanCnt = math.random(1, 100)
                    if bindCnt >= bindRanCnt then
                        bind = true
                    else
                        bind = false
                    end
                end

            else

                if bagGrid.bind and bindRule == 1 then
                    bind = true
                else
                    local bindRanCnt = math.random(1, 100)
                    if bindCnt >= bindRanCnt then
                        bind = true
                    else
                        bind = false
                    end
                end

            end

            cnt = math.random(cnt, cnt1)

            local ret, grid, realCnt = BagLogic.addItem(human, id, bind, cnt, "item_libao", qualityOut, nil, nil, strengthenLv)
            nTempGrid = Grid.create(nil, id, realCnt, bind, qualityOut)

            if ItemDefine.is_spobj[id] or ItemDefine.isItem(id) then
                if not libaoGrids[id] then
                    libaoGrids[id] = 0
                end
                libaoGrids[id] = libaoGrids[id] + cnt
            else
                libaoGrids[#libaoGrids + 1] = nTempGrid
            end

            if not ret and not ItemDefine.is_spobj[id] then
                assert(nil, id)
            end

        end

    end

    --抽取道具逻辑
    if arg2 then
        local without = {}
        --getLibaoWithoutList(without, arg2, data.itemID)
        for i = 1, arg2[0] do
            --列表2格式：{[0]=抽选数量，{抽选权重, 物品ID，物品数量1，物品数量2, 绑定规则, 绑定几率，{排除品质}，强化等级, 职业，性别}，……}

            local index = RandomLogic.getRandom5(human, arg2, without, 1, 9, 10)
            without[#without + 1] = index
            local conf = arg2[index]

            local id = conf[2]
            local cnt = conf[3]
            local cnt1 = conf[4]
            local bindRule = conf[5]
            local bindCnt = conf[6]
            local qualityOut = conf[7]
            local strengthenLv = conf[8]
            --            local shenbing =  conf[9]
            --            local sex = conf[10]

            cnt = math.random(cnt, cnt1)
            if itemIndex then
                if itemBind and bindRule == 1 then
                    bind = true
                else
                    local bindRanCnt = math.random(1, 100)
                    if bindCnt >= bindRanCnt then
                        bind = true
                    else
                        bind = false
                    end
                end

            else

                if bagGrid.bind and bindRule == 1 then
                    bind = true
                else
                    local bindRanCnt = math.random(1, 100)
                    if bindCnt >= bindRanCnt then
                        bind = true
                    else
                        bind = false
                    end
                end

            end

            local ret, grid, realCnt = BagLogic.addItem(human, id, bind, cnt, "item_libao", qualityOut, nil, nil, strengthenLv)
            nTempGrid = Grid.create(nil, id, realCnt, bind, qualityOut)

            if ItemDefine.is_spobj[id] or ItemDefine.isItem(id) then
                if not libaoGrids[id] then
                    libaoGrids[id] = 0
                end
                libaoGrids[id] = libaoGrids[id] + cnt
            else
                libaoGrids[#libaoGrids + 1] = nTempGrid
            end

            if not ret and not ItemDefine.is_spobj[id] then
                assert(nil, data.itemID.."-"..id)
            end
        end
    end

    if itemIndex then
        BagLogic.delItemByIndex(human, itemIndex, itemCnt, "item_libao")
    end

    local useGrid = BagLogic.getGridByIndex(human, index)

    local nTipContent = ""
    local msgRet = Msg.gc.GC_MULTI_BROADCAST
    msgRet.type = Lang.MOUSE
    msgRet.msgs[0] = 0
    for key, grid in pairs(libaoGrids) do
        local typeClass = type(grid)
        if typeClass == "cdata" or typeClass == "table" then
            nTipContent = nTipContent .. HtmlUtil.fontItemId3(grid.id, grid.cnt) .. "\n"
            msgRet.msgs[0] = msgRet.msgs[0] + 1
            local color = ItemDefine.getColorByGrid(grid)
            msgRet.msgs[msgRet.msgs[0]] = HtmlUtil.fontItemId3(grid.id, grid.cnt, color)
            if useGrid then
                if ExcelItem.libaoGoodItem[grid.id] then
                    local content = string.format(
                    Lang.ITEM_GET_GOOD_EQUIP,
                    HtmlUtil.font("", "#56E3F7") .. HtmlUtil.fontName(human.name, human._id) ..HtmlUtil.font("", "#56E3F7"),
                    HtmlUtil.fontItemNoCnt(useGrid),
                    HtmlUtil.fontItem(grid)
                    )
                    Broadcast.sendBroadcast2World(Lang.GROSSIP+Lang.UP, content)
                end
            end
        elseif typeClass == "number" then
            nTipContent = nTipContent .. HtmlUtil.fontItemId3(key, grid) .. "\n" 
            msgRet.msgs[0] = msgRet.msgs[0] + 1
            msgRet.msgs[msgRet.msgs[0]] = HtmlUtil.fontItemId3(key, grid)
            if useGrid then
                if ExcelItem.libaoGoodItem[key] then
                    local content = string.format(
                    Lang.ITEM_GET_GOOD_EQUIP,
                    HtmlUtil.font("【", "#56E3F7") .. HtmlUtil.fontName(human.name, human._id) ..HtmlUtil.font("】", "#56E3F7"),
                    HtmlUtil.fontItemNoCnt(useGrid),
                    HtmlUtil.fontItemId3(key, grid)
                    )
                    Broadcast.sendBroadcast2World(Lang.GROSSIP+Lang.UP, content)
                    --end
                end
            end
        end
    end

    if msgRet.msgs[0] > 0 then
        Broadcast.sendBroadcast(human, Lang.MOUSE, nTipContent)
        --Msg.send(msgRet, human.fd)
    end
    return true
end

-- 得到礼包展示物品格子
local libaoShowGrid = {}
function getLiabaoShowGrid(itemID)
    if libaoShowGrid[itemID] then
        return libaoShowGrid[itemID]
    end
    local command = ItemDefine.getValue(itemID, "command")
    if not command or command[1] ~= "libao" or not command[2] or not command[2][1] then
        return
    end
    libaoShowGrid[itemID] = {}
    local len = 0
    local arg1 = command[2][1]
    local bind
    for i = 1, #arg1 do
        local conf = arg1[i]
        local id = conf[1]
        local cnt = conf[2]
        local cnt1 = conf[3]
        --        local bindRule = conf[4]
        local bindCnt = conf[5]
        local qualityOut = conf[6]
        --        local strengthenLv = conf[7]
        local bindRanCnt = math.random(1, 100)
        if bindCnt >= bindRanCnt then
            bind = true
        else
            bind = false
        end
        cnt = math.random(cnt, cnt1)
        len = len + 1
        libaoShowGrid[itemID][len] = {}
        Grid.create(libaoShowGrid[itemID][len], id, cnt, bind, qualityOut)
        libaoShowGrid[itemID][len].sbid = conf[8]
        libaoShowGrid[itemID][len].sex = conf[9]
    end
    return libaoShowGrid[itemID]
end

function cmd.lvup(human, addlv)
    if type(addlv) ~= "number" or addlv < 1 or addlv > RoleAttr.ROLE_MAX_LV then
        return send_err(human, Lang.ITEM_ERR_CONF_ERR)
    end

    if human.db.lv >= RoleAttr.ROLE_MAX_LV then
        return send_err(human, Lang.ITEM_ERR_U_MAX_LV)
    end

    addlv = math.min(RoleAttr.ROLE_MAX_LV - human.db.lv, addlv)
    human.db.lv = human.db.lv + addlv
    ObjHuman.onLvUpCB(human, human.db.lv - addlv, human.db.lv)
    return true
end

local sumLvOrExp = 0
function cmd.lvuporexp(human, arg1, arg2, arg3)
    local index, cnt, left = data.index, data.cnt, data.left
    if type(arg2) ~= "number" or type(arg1) ~= "number" or type(arg3) ~= "number" then
        return send_err(human, Lang.ITEM_ERR_CONF_ERR)
    end

    local nLv = human.db.lv
    if nLv < arg1 then
        return cmd.lvup(human, arg2)
    else
        if cnt == left then	--第一次
            sumLvOrExp = 0
        end

        if arg3 > 0 then
            sumLvOrExp = sumLvOrExp + arg3
            if sumLvOrExp > 0 and left == 1 then
                ObjHuman.addExp(human, sumLvOrExp)
                local useDesc = getUseDesc(human, index)
                if useDesc then
                    useDesc = string.format(useDesc, sumLvOrExp)
                    Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
                end
            end
        end
        return true
    end
end

local sumPetLvOrExp = 0
local canUsePetExp = 0
function cmd.petlvuporexp(human, arg1, arg2, arg3)
    local index, cnt, left = data.index, data.cnt, data.left
    if type(arg2) ~= "number" or type(arg1) ~= "number" or type(arg3) ~= "number" then
        return send_err(human, Lang.ITEM_ERR_CONF_ERR)
    end

    local nLv = PetLogic2.getCombatPetLv(human)
    if not nLv then
        return false
    elseif nLv == -1 then
        Broadcast.sendBroadcast(human, Lang.DOWN, Lang.PET_NOT_HAVE_COMBAT_ID)
        return false
    end

    if nLv < arg1 then
        return PetLogic2.addLv(human, arg2, nil)
    else
        if cnt == left then	--第一次
            sumPetLvOrExp = 0
            canUsePetExp = PetLogic2.canUseExpItem(human)
        end

        if canUsePetExp == false or canUsePetExp == 0 then
            return false
        end

        if arg3 > 0 then
            sumPetLvOrExp = sumPetLvOrExp + arg3
            local nResult = true
            if sumPetLvOrExp > canUsePetExp then
                nResult = false
            end

            if (left == 1 or nResult == false) and sumPetLvOrExp > 0 then	--最后一次
                nResult = PetLogic2.addLv(human, nil, sumPetLvOrExp)
                local useDesc = getUseDesc(human, index)
                if useDesc then
                    useDesc = string.format(useDesc, sumPetLvOrExp)
                    Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
                end
            end
            return (nResult == true) and true or false 
        end
    end
    return false
end

function cmd.petstar(human, arg1, arg2, arg3)
    local index, cnt, left = data.index, data.cnt, data.left
    if type(arg2) ~= "number" or type(arg1) ~= "number" then
        return send_err(human, Lang.ITEM_ERR_CONF_ERR)
    end

    if left == 1 then	--最后一次
        return PetLogic2.addStar(human, arg1, arg2)
    end
    return false
end

local sumAwake = 0
function cmd.awake(human, arg1)
    local index, left = data.index, data.left
    if type(arg1) ~= "number" then
        return send_err(human, Lang.ITEM_ERR_CONF_ERR)
    end

    if Cmds.passive.awake(human) then
        return send_err(human, Lang.ITEM_ERR_AWAKE_ALRD)
    end

    local nResult = ObjHuman.canAddAwake(human)
    if not nResult then
        return send_err(human, Lang.ITEM_ERR_AWAKE_FULL)
    end

    sumAwake = sumAwake + arg1
    if sumAwake > 0 and left == 1 then
        ObjHuman.addAwake(human, sumAwake)
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumLvOrExp)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    return true
end

function cmd.deccopytime(human, arg1)
    for i = 0, human.db.copyTimesLen-1 do
        if human.db.copyTimes[i].copy_id == arg1 then
			if human.db.copyTimes[i].times and human.db.copyTimes[i].times > 0 then
				human.db.copyTimes[i].times =  human.db.copyTimes[i].times - 1
				TaskDuanceng.onCopyCntChange(human)
				ActivityNotify.CG_ACTIVITY_COPY_UPDATE(human)
				send_err(human, Lang.ITEM_DEC_COPY_CNT)
				return true	
			end
        end
    end
    
	send_err(human, Lang.ITEM_ERR_NO_ENTER_COPY)
    return false
end

function cmd.tiaozhanpoint(human, arg1)
	local maxTZ = human.db.wsAddTimes * WSConfig[1].addTZZ + WSConfig[1].totalTZ
	
	if human.db.remainTZ + arg1 > maxTZ then
		send_err(human, Lang.ITEM_ERR_MAX_TIAOZHAN)
        return false
	end

    human.db.remainTZ = human.db.remainTZ + arg1
    Wushuang.sendTZTimes(human)
	
	send_err(human, string.format(Lang.ITEM_TIAOZHAN, arg1))
    
    return true
end

function cmd.mp(human, arg1)


    local objSceneID = human.scene_id
    local objCopyID = Copy.sceneID2CopyID[objSceneID]
    if objCopyID == CopyDefine.COPY_PETCOPY_ID then
        return send_err(human, Lang.ITEM_ERR_IN_WSL)
    elseif objCopyID == CopyDefine.COPY_JINGJI_ID then
        return send_err(human, Lang.ITEM_ERR_IN_JINGJI)
    end

    local mpMax = ObjHuman.getMpMax(human)
    if mpMax <= human.db.mp then
        return send_err(human, Lang.ITEM_ERR_MP_FULL)
    end
    if arg1 > 1 then			-- add value
        ObjHuman.setMp(human, human.db.mp+arg1)
    else						-- add rate
        ObjHuman.setMp(human, ObjHuman.human.db.mp+mpMax * arg1)
    end
    return true
end

function cmd.petskill(human, skill_id)
    if human.db.pet_skill[skill_id] then
        return send_err(human, Lang.ITEM_ERR_PET_SKILL_LEARNED)
    end
    local cf = ExcelSkill.Skill[skill_id]
    if not cf then
        assert(nil, skill_id)
    end
    human.db.pet_skill[skill_id] = 1
    PetHandler.send_GC_PET_SKILL_UPGRADE(human, skill_id)
    return true
end

local sumExp = 0
function cmd.exp(human, ntype, value, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    if cnt == left then	--第一次
        sumExp = 0
    end

    local expAdd = 0
    if ntype == 1 then
        if type(value1) ~= "number" then
            return
        end
        if value1 < 1 then
            return
        end

        if value2 then
            if type(value2) ~= "number" then
                return
            end

            if value2 < 1 or value2 < value1 then
                return
            end
            expAdd = math.random(value1, value2)
        else
            expAdd = value1
        end
    else
        expAdd = ExcelLevelRewardConf[value] and ExcelLevelRewardConf[value][human.db.lv].exp or 0
    end

    sumExp = sumExp + expAdd

    if sumExp > 0 and left == 1 then
        ObjHuman.addExp(human, sumExp)
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumExp)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    return true
end

function cmd.skill(human, skillID, skillLv, isNoLoss)
    local target = Obj.objs[useSkillData.recv_id]
    if not Skill.add(human, skillID, useSkillData.tx, useSkillData.ty, human.x, human.y, target, skillLv) then
        return send_err(human, Lang.ITEM_ERR_USE_SKILL)
    end
    useSkillData.tx = nil
    useSkillData.ty = nil
    useSkillData.recv_id = nil
    human.db.cool[ExcelItem.item[data.itemID].coolGroup] = os.time()
    BagLogic.sendBagItemChange(human, data.index)
    return isNoLoss~=1
end

local sumYinliang = 0
function cmd.yinliang(human, ntype, value, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    local addYinliang = 0
    if cnt == left then	--第一次
        sumYinliang = 0
    end
    if ntype == 1 then
        if type(value1) ~= "number" then
            return
        end
        if value1 < 1 then
            return
        end

        if value2 then
            if type(value2) ~= "number" then
                return
            end

            if value2 < 1 or value2 < value1 then
                return
            end
            addYinliang = math.random(value1, value2)
            if not ObjHuman.canAddYinliang(human, addYinliang) then
                return send_err(human, Lang.ITEM_ERR_YINLIANG_FULL)
            end
        else
            addYinliang = value1
            if not ObjHuman.canAddYinliang(human, addYinliang) then
                return send_err(human, Lang.ITEM_ERR_YINLIANG_FULL)
            end
        end
    else
        addYinliang = ExcelLevelRewardConf[value] and ExcelLevelRewardConf[value][human.db.lv].yinliang or 0
        if addYinliang > 0 then
            if not ObjHuman.canAddYinliang(human, addYinliang) then
                return send_err(human, Lang.ITEM_ERR_YINLIANG_FULL)
            end
        end
    end
    sumYinliang = sumYinliang + addYinliang

    if sumYinliang > 0 and left == 1 then	--最后一次
        ObjHuman.addYinliang(human, sumYinliang, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumYinliang)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end

    return true
end

local sumYuanbao = 0
function cmd.yuanbao(human, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    local nAddYuanBao = 0
    if type(value1) ~= "number" then
        return
    end

    if value1 < 1 then
        return
    end

    if cnt == left then	--第一次
        sumYuanbao = 0
    end

    if value2 then
        if type(value2) ~= "number" then
            return
        end
        if value2 < 1 or value1 > value2 then
            return
        end
        nAddYuanBao = math.random(value1, value2)
    else
        nAddYuanBao = value1
    end

    sumYuanbao = sumYuanbao + nAddYuanBao

    if sumYuanbao > 0 and left == 1 then	--最后一次
        ObjHuman.addYuanbao(human, sumYuanbao, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumYuanbao)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end

    return true
end

local sumBindYuanbao = 0
function cmd.bind_yuanbao(human, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    local nAddBYuanBao = 0
    if type(value1) ~= "number" then
        return
    end

    if value1 < 1 then
        return
    end

    if cnt == left then	--第一次
        sumBindYuanbao = 0
    end

    if value2 then
        if type(value2) ~= "number" then
            return
        end
        if value2 < 1 or value1 > value2 then
            return
        end
        nAddBYuanBao = math.random(value1, value2)
    else
        nAddBYuanBao = value1
    end

    sumBindYuanbao = sumBindYuanbao + nAddBYuanBao

    if sumBindYuanbao > 0 and left == 1 then	--最后一次
        ObjHuman.addBindYuanbao(human, sumBindYuanbao, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumBindYuanbao)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end

    return true
end

function cmd.chongzhi(human, value)
    local msg = Msg.lw.LW_GM
    msg.cmd = "pay"
    msg.arg = ""..value
    Msg.send2world(msg, human._id)
    return true
end

local sumZhanGong = 0
function cmd.zhangong(human, ntype, value, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    if cnt == left then
        sumZhanGong = 0
    end
    local nAddZhanGong = 0
    local nResult = 0
    if ntype == 1 then
        if type(value1) ~= "number" then
            return
        end
        if value1 < 1 then
            return
        end

        if cnt == left then	--第一次
        end

        if value2 then
            if type(value2) ~= "number" then
                return
            end

            if value2 < 1 or value2 < value1 then
                return
            end
            nAddZhanGong = math.random(value1, value2)
            nResult = ObjHuman.canAddZhanGong(human, sumZhanGong)
            if nResult == -1 then
                send_err(human, Lang.ITEM_ERR_ZHANGONG_FULL)
            end
        else
            nAddZhanGong = value1
            nResult = ObjHuman.canAddZhanGong(human, sumZhanGong)
            if nResult == -1 then
                send_err(human, Lang.ITEM_ERR_ZHANGONG_FULL)
            end
        end
    else
        nAddZhanGong = ExcelLevelRewardConf[value] and ExcelLevelRewardConf[value][human.db.lv].zhangong or 0
        if nAddZhanGong > 0 then
            nResult = ObjHuman.canAddZhanGong(human, sumZhanGong)
            if nResult == -1 then
                send_err(human, Lang.ITEM_ERR_ZHANGONG_FULL)
            end
        end
    end
    if nResult == 1 or nResult == 2 then
        sumZhanGong = sumZhanGong + nAddZhanGong
    end

    if sumZhanGong > 0 and (left == 1 or nResult == 2 or nResult == -1) then	--最后一次或者连续使用到达限制
        ObjHuman.addZhangong(human, sumZhanGong, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumZhanGong)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    if nResult == -1 then
        return false
    end
    if nResult == 1 or nResult == 2 then
        return true
    end
    return false
end

local sumWeiwang = 0
function cmd.weiwang(human, ntype, value, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    if cnt == left then
        sumWeiwang = 0
    end
    local nAddWeiwang = 0
    if ntype == 1 then
        if type(value1) ~= "number" then
            return
        end
        if value1 < 1 then
            return
        end

        if cnt == left then --第一次
        end
        if value2 then
            if type(value2) ~= "number" then
                return
            end

            if value2 < 1 or value2 < value1 then
                return
            end
            nAddWeiwang = math.random(value1, value2)
        else
            nAddWeiwang = value1
        end
    else
        nAddWeiwang = ExcelLevelRewardConf[value] and ExcelLevelRewardConf[value][human.db.lv].weiwang or 0
    end
    sumWeiwang = sumWeiwang + nAddWeiwang
    if sumWeiwang > 0 and left == 1 then
        ObjHuman.addPrestige(human, sumWeiwang, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumWeiwang)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    return true
end

local sumRongyu = 0
function cmd.rongyu(human, ntype, value, value1, value2)
    local index, cnt, left = data.index, data.cnt, data.left
    if cnt == left then
        sumRongyu = 0
    end
    local nAddRongyu = 0
    if ntype == 1 then
        if type(value1) ~= "number" then
            return
        end
        if value1 < 1 then
            return
        end

        if cnt == left then --第一次
        end
        if value2 then
            if type(value2) ~= "number" then
                return
            end
            if value2 < 1 or value2 < value1 then
                return
            end
            nAddRongyu = math.random(value1, value2)
        else
            nAddRongyu = value1
        end
    else
        nAddRongyu = ExcelLevelRewardConf[value] and ExcelLevelRewardConf[value][human.db.lv].rongyu or 0
    end
    sumRongyu = sumRongyu + nAddRongyu
    if sumRongyu > 0 and left == 1 then
        ObjHuman.addRongyu(human, sumRongyu, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumRongyu)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    return true
end

local sumWuShuang = 0
function cmd.wushuang(human, ws)
    local index, cnt, left = data.index, data.cnt, data.left
    if type(ws) ~= "number" then
        return
    end

    if ws < 1 then
        return
    end

    if cnt == left then	--第一次
        sumWuShuang = 0
    end
    sumWuShuang = sumWuShuang + ws

    if sumWuShuang > 0 and left == 1 then	--最后一次
        ObjHuman.addWushuang(human, sumWuShuang, "item_use")
        local useDesc = getUseDesc(human, index)
        if useDesc then
            useDesc = string.format(useDesc, sumWuShuang)
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
    end
    return true
end

function cmd.history_yuanbao(human, val)
    local oldYB = human.db.historyYuanbao
    human.db.historyYuanbao = human.db.historyYuanbao + val   -- 累计充值元宝
    human.attr[RoleDefine.HISTORY_CHONGZHI] = human.db.historyYuanbao
    VipLogic.setRewardCanGet(human, oldYB)
    ObjHuman.sendAttr(human, RoleDefine.HISTORY_CHONGZHI)
    return true
end

function cmd.openlaba(human)
    local msgRet = Msg.gc.GC_CHAT_LABA
    Msg.send(msgRet, human.fd)
    return
end




function cmd.flower(human)
    cmd.panel(human, PanelDefine.PANEL_FLOWER, data.itemID)
end

function cmd.panel(human, panelID)
    if ItemDefine.isGem(id) then
        panelID = 8
    end
    local msgRet = Msg.gc.GC_OPEN_PANEL
    msgRet.id = panelID
    msgRet.values[0] = 0
    Msg.send(msgRet, human.fd)
end

function cmd.openmake(human, cate, targetID)
    local msgRet = Msg.gc.GC_REFINE_OPEN
    msgRet.cate = cate
    msgRet.targetID = targetID
    Msg.send(msgRet, human.fd)
end

function cmd.changename(human)
    local msgRet = Msg.gc.GC_NAME_CHANGE_PANEL_OPEN
    Msg.send(msgRet, human.fd)
end

local sumPetCnt= 0
local canUsePetItemCnt = 0
function cmd.addPetExp(human)
    local cnt, left = data.cnt, data.left
    if cnt == left then	--第一次
        sumPetCnt = 0
        canUsePetItemCnt = PetLogic2.canUseExpItem(human, cnt, nil, data.itemID)
    end

    if canUsePetItemCnt == false or canUsePetItemCnt <= 0 then
        return false
    end

    sumPetCnt = sumPetCnt + 1
    local nResult = true
    if sumPetCnt > canUsePetItemCnt then
        nResult = false
    end

    if (left == 1 or nResult == false) and sumPetCnt > 0 then	--最后一次
        if not PetLogic2.addExpItem2(human, nil, data.itemID, sumPetCnt) then
            return false
        end
    end
    if nResult == false then
        return false
    end
    return true
end


function cmd.go(human, mapid, x, y, staticID, type)
    local mm = Msg.gc.GC_ITEM_GO_TO
    mm.mapid = mapid
    mm.x = x
    mm.y = y
    mm.staticID = staticID
    mm.type = type
    Msg.send(mm, human.fd)
    return false
end


function cmd.horseactive(human, horseid, time, itemId, itemCnt)--, preID)
    if not horseid then
        return false
    end
    if not time or time == 0 then
        if HorseLogic.jihuo(human, horseid, true, 2, time, data.itemID) then
        else
            return false
        end
    else
        if time < 0 then
            return false
        end

        if not HorseLogic.jihuoLimit(human, horseid, time, itemId, itemCnt) then
            return false
        end
    end
    HorseLogic.huanhua(human, horseid)
    return true
end

function cmd.petactive(human, petid, time, itemId, itemCnt)--, preID)
    if not petid then
        return false
    end
    if not time or time == 0 then
        return false
    else
        if time < 0 then
            return false
        end

        if not PetLogic.jihuoLimitPet(human, petid, time, itemId, itemCnt) then
            return false
        end
    end
    return true
end
function cmd.baowuactive(human, baowuid, time, itemId, itemCnt)
      if not baowuid then
        return false
    end
    if not time or time == 0 then
        return false
    else
        if time < 0 then
            return false
        end

        if not BaowuLogic.jihuoLimitBaowu(human, baowuid, time, itemId, itemCnt) then
            return false
        end
    end
    return true
end
function cmd.horselvuporexp(human, lv, addlv, addstar, addExp)
    if HorseLogic.CanStage(human) then
        send_err(human, Lang.ITEM_ERR_HORSESTAGE)
        return false
    end

    local nHorseLv = HorseLogic.getHorseLv(human)

    if nHorseLv < lv then
        if addlv > 0 then
            HorseLogic.addLv(human, addlv)
        elseif addstar > 0 then
            HorseLogic.addStarLv(human, addstar)
        end
    else
        HorseLogic.addExp(human, addExp)
    end
    return true
end

function cmd.baowulvuporexp(human, lv, addLv, addExp)
    if not BaowuLogic._checkStatus(human, human.db.combatBaowu, true) then
        return false
    end

    local nCombatBaoWuLv = BaowuLogic.onGetCombatBaoWuLV(human)

    if nCombatBaoWuLv then
        if nCombatBaoWuLv < lv then
            if addLv > 0 then
                if not BaowuLogic._addLv(human, human.db.combatBaowu, addLv, true) then
                    return false
                end
            end
        else
            if not BaowuLogic._addExp(human, human.db.combatBaowu, addExp, true) then
                return false
            end
        end
        return true
    end
    return false
end

function cmd.sblvuporstarlv(human, lv, addLv, addStar)
    if not ShenbingLogic.checkStatus(human, human.db.putonShenbing, true) then
        return false
    end

    local nCombatSBLv = ShenbingLogic.onGetCombatShengBingLv(human)

    if nCombatSBLv then
        if nCombatSBLv < lv then
            if addLv > 0 then
                if not ShenbingLogic.onAddLv(human, human.db.putonShenbing, addLv, true) then
                    return false
                end
            end
        else
            if not ShenbingLogic.onAddStar(human, human.db.putonShenbing, addStar, true) then
                return false
            end
        end
        return true
    end
    return false
end

--属性果实
function cmd.attr(human)--, attrID, attrValue)
    local record
    for i = 0, human.db.attr_itemLen - 1 do
        if human.db.attr_item[i].itemid == data.itemID then
            record = human.db.attr_item[i]
            break
        end
    end
    if record and record.cnt >= human.db.lv *4 then
        send_err(human, Lang.ITEM_ERR_ATTR_FULL)
        return
    end
    if record == nil then
        record = human.db.attr_item[human.db.attr_itemLen]
        human.db.attr_itemLen = human.db.attr_itemLen + 1
        record.itemid = data.itemID
        record.cnt = 0
    end
    record.cnt = record.cnt + 1
    data.reCalc = true
    return true
end



-- 属性果实增加属性
function doAttrAddAttr(human)
    for i = 0, human.db.attr_itemLen - 1 do
        local record = human.db.attr_item[i]
        local command = ItemDefine.getValue(record.itemid, "command")
        if command and command[1] == "attr" and command[2] and command[3] then
            if human.attr[command[2]] then
                human.attr[command[2]] = human.attr[command[2]]  + command[3] * record.cnt
            end
        end
    end
end
function use(human, index, cnt, no_send_err, batchUse)
    data.no_send_err = no_send_err

    if human.db.hp < 1 then
        send_err(human, Lang.ITEM_ERR_DEAD_CANT_USE)
        return false
    end

    local grid = BagLogic.getGridByIndex(human, index)
    if not grid then
        send_err(human, Lang.ITEM_ERR_GRID_NOT_EXIST)
        return false
    end

    local itemID = grid.id
    if grid.id == 0 or cnt < 1 or cnt > grid.cnt then
        send_err(human, Lang.ITEM_ERR_NUM_ERR)
        return false
    end
    local os_time = os.time()
    if grid.lifeTime > 0 and os_time > grid.lifeTime then
        BagLogic.delGridByIndex(human, index, "grid_over_time")
        Broadcast.sendBroadcast(human, Lang.CHAT+Lang.MOUSE, string.format(Lang.BAG_GRID_OVER_TIME, HtmlUtil.fontItem(grid)))
        return false
    end

    local cntLimit = 0
    if type(grid.data.item) == "cdata" and grid.data.item.cntLimit then
        cntLimit = grid.data.item.cntLimit
    end

    if cntLimit > 0  and cntLimit < 1 then
        send_err(human, Lang.ITEM_ERR_NUM_ERR)
        return false
    end

    local command = ItemDefine.getValue(itemID, "command")

    if not command then
        send_err(human, Lang.ITEM_ERR_NOT_ITEM)
        return false
    end

    if not command[1] then
        if itemID == 10037 then
          send_err(human, Lang.ITEM_ERR_CANT_USE)
        end
        return false
    end

    local useMiddle = ItemDefine.getValue(grid.id,"canUseMiddle")
    if useMiddle == 1 and Config.IS_MIDDLE == true then
        return send_err(human,Lang.MIDDLE_CANNOT_USE_ITME)
    end
    print("use itemid is ", itemID, " cnt is ", cnt, " cmd is ", command[1])

    local sex = ItemDefine.getValue(itemID, "sex")
    if sex ~= 0 and human.db.sex ~= sex then
        send_err(human, Lang.ITEM_NOT_FIX_SEX)
        return false
    end
    

    if not cmd[command[1]] then
        send_err(human, Lang.ITEM_ERR_NO_CMD)
        return false
    end

    data.itemID = itemID
    data.pos_in_bag = index
    local left = cnt
    local ac
    while 0 < left do
        if human.db.lv < ItemDefine.getValue(itemID, "lv") then
            send_err(human, Lang.ITEM_ERR_LV)
            ac = false
            break
        end

        local cntOneDay = ItemDefine.getValue(itemID, "cntOneDay")
        if cntOneDay > 0 then
            if not BagLogic.checkDayCntUse(human, itemID, cntOneDay, cnt) then
                send_err(human, Lang.ITEM_ERR_CAN_USE_CNT_ENOUGH, HtmlUtil.fontItemId(itemID, 1), cntOneDay)
                ac = false
                break
            end
        end

        local useGroup = ItemDefine.getValue(itemID, "useGroup")
        local useGroupDayCnt = ItemDefine.getValue(itemID, "groupCntOneDay")
        if useGroup ~= 0 and useGroupDayCnt > 0 then
            if not BagLogic.checkUseGroupDayCnt(human, itemID, useGroup, useGroupDayCnt, cnt) then
              if human.attr[RoleDefine.VIP_LEVEL] >= 10 then
                send_err(human, Lang.ITEM_ERR_GROUPUSE_CNT_NOT_ENOUGH_1)
                ac = false
                break
              else
                send_err(human, Lang.ITEM_ERR_GROUPUSE_CNT_NOT_ENOUGH)
                ac = false
                break
              end
            end
        end

        local coolGroup = ItemDefine.getValue(itemID, "coolGroup")
        local coolTime = ItemDefine.getValue(itemID, "coolTime")
        if coolGroup ~= 0 and coolTime ~= 0 then
            if not BagLogic.checkUseCool(human, coolGroup, coolTime) then
                send_err(human, Lang.ITEM_ERR_IN_CD)
                ac = false
                break
            end
        end
        data.index = index
        data.cnt = cnt
        data.left = left
        data.itemID = itemID
        local nResult = cmd[command[1]](human, command[2], command[3], command[4], command[5], command[6])
        if nResult then
            ac = true
            if coolGroup ~= 0 and coolTime ~= 0 then
                BagLogic.addItemUseCool(human, coolGroup, os_time)
            end
            if cntOneDay > 0 then
                BagLogic.addDayCntUse(human, itemID, cnt)
            end
            if useGroupDayCnt > 0 then
                BagLogic.addDayCntUseGroup(human, itemID, cnt, useGroup)
            end
            --            if itemID ~= PetConfig[1].itemId and itemID ~= PetConfig[2].itemId and itemID ~= PetConfig[3].itemId then
            BagLogic.delItemByIndex(human, index, 1, "item_use", true)
            --            end
            left = left - 1
        else
            ac = false
            break
        end
    end

    if left < cnt and not batchUse then
        BagLogic.sendBagItemChange(human, index)
        TaskCallbacks.taskUseItemCB(human, itemID)
        local showUseDesc = ItemDefine.getValue(itemID, "showUseDesc")
        local useDesc = ItemDefine.getValue(itemID, "useDesc")
        if showUseDesc and showUseDesc == 0 and useDesc and #useDesc ~= 0 then
            Broadcast.sendBroadcast(human, Lang.MOUSE, useDesc)
        end
        if data.reCalc then  --重新计算属性
            ObjHuman.doCalc(human)
        end
    end
    return ac, cnt - left
end
